package com.tchy.cloud.controller;

import com.tchy.cloud.entity.AOfficialWhEntity;
import com.tchy.cloud.entity.TPushRecords;
import com.tchy.cloud.tools.YouMengUtil;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.jboss.logging.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.entity.TArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 推送通知管理
 * Created by zjy on 2015/9/22.
 */
@Controller
@RequestMapping("/pushRecordsController")
public class PushRecordsController {

    private static final Logger logger = Logger.getLogger(PushRecordsController.class);

    @Autowired
    private SystemService systemService;

    private String message;


    /**
     * 推送通知管理列表页
     * @return
     */
    @RequestMapping(params = "pushRecordsList")
    public ModelAndView pushRecordsList(){
        return new ModelAndView("tcdev/pushRecords/pushRecordsList");
    }


    /**
     * 推送通知管理列表
     * @param pushRecords
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(TPushRecords pushRecords,HttpServletRequest request,HttpServletResponse response,DataGrid dataGrid){


        CriteriaQuery cq = new CriteriaQuery(TPushRecords.class,dataGrid);

        cq.add();
        // 查询条件组装
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, pushRecords, request.getParameterMap());
        this.systemService.getDataGridReturn(cq,true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 跳转到修改转视图
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(TPushRecords pushRecords,
                                    HttpServletRequest req) {


        if (pushRecords.getId() != null) {
            pushRecords = systemService.getEntity(TPushRecords.class, pushRecords.getId());

            req.setAttribute("pushRecords", pushRecords);

        }


        return new ModelAndView("tcdev/pushRecords/pushRecords");
    }

    /**
     * 选择用户弹出窗口 mini用户信息列表页
     *
     * @return
     */
    @RequestMapping(params = "miniUserList")
    public ModelAndView miniUserList(HttpServletRequest request) {

        return new ModelAndView("tcdev/pushRecords/miniUserList");
    }

    /**
     * 系统公告
     * @param request
     * @return
     */
    @RequestMapping(params = "miniArticle")
    public ModelAndView miniArticle(HttpServletRequest request) {

        return new ModelAndView("tcdev/pushRecords/miniArticleList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "articleDatagrid")
    public void articleDatagrid(TArticle article, HttpServletRequest request,
                                HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(TArticle.class, dataGrid);

        cq.eq("isPublish","1");//有效
        cq.addOrder("id", SortDirection.desc);
        cq.add();

        // 查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, article, request.getParameterMap());
        this.systemService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 获取用户信息列表
     * @param request request
     * @return 处理结果信息
     */
    @RequestMapping(params = "addUserList")
    public void addUserList(TSUser user, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

        CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);


        cq.add();
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);

        this.systemService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 新闻文章
     * @param request
     * @return
     */
    @RequestMapping(params = "miniOfficialWhList")
    public ModelAndView miniOfficialWhList(HttpServletRequest request) {

        return new ModelAndView("tcdev/pushRecords/miniOfficialWhList");
    }
    /**
     * 文章管理列表
     * @param officialWh
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "miniOfficialWhDatagrid")
    public void partnerApplyDatagrid(AOfficialWhEntity officialWh, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid){
        CriteriaQuery cq = new CriteriaQuery(AOfficialWhEntity.class,dataGrid);


        Map<String,Object> orderMap = new HashMap<String,Object>();
        orderMap.put("writeTime","desc");
        orderMap.put("status","asc");

        cq.setOrder(orderMap);
        cq.eq("deleted",0);
        cq.eq("status",1);
        cq.add();

        // 查询条件组装
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, officialWh, request.getParameterMap());
        this.systemService.getDataGridReturn(cq,true);

        List owList = dataGrid.getResults();

        for(int i = 0; i < owList.size(); i++){

            AOfficialWhEntity officialWh1 = (AOfficialWhEntity)owList.get(i);
            //翻译
            List<String> columnName = systemService.findListbySql(
                    "select t2.title from a_official_columns t1 \n" +
                            "left join a_columns t2 on t1.columns_id = t2.columns_id \n" +
                            "where t1.article_id = " + officialWh1.getArticleId());

            officialWh1.setFactorColumnName(StringUtil.listToStringSlipStr(columnName,","));

        }

        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 添加推送通知管理
     *
     * @param pushRecords
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(TPushRecords pushRecords, HttpServletRequest request) {

        AjaxJson j = new AjaxJson();
        if (pushRecords.getId() != null) {

            try {

                TPushRecords c = systemService.get(TPushRecords.class, pushRecords.getId());

                MyBeanUtils.copyBeanNotNull2Bean(pushRecords, c);

                systemService.saveOrUpdate(c);

                message = MutiLangUtil.paramUpdSuccess("推送["+pushRecords.getTitle()+"]");

            } catch (Exception e) {
                e.printStackTrace();
                message = MutiLangUtil.paramUpdFail("推送["+pushRecords.getTitle()+"]");
            }
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } else {

            try {

                TSUser user = ResourceUtil.getSessionUserName();

                pushRecords.setCreateTime(new Date());//创建时间
                pushRecords.setSender(user);//发送者
//                pushRecords.setObjectType(0);//系统为0
                int openType = 0;//APP中打开方式
                if(pushRecords.getObjectType() == 102){//102表示新闻公告
                    openType = 1;

                }else if(pushRecords.getObjectType() == 103){
                    openType = 2;
                }else{
//                    pushRecords.setArticle(null);
                }

                String pushType = request.getParameter("pushType");

                if(StringUtil.isNotEmpty(pushRecords.getObjectId())){
                    pushRecords.setObjectId(pushRecords.getObjectId().replaceAll(",",""));
                }

                systemService.save(pushRecords);

                boolean sendBoo = false;//默认为false
                //附属参数
                Map<String,String> param = new HashMap<String,String>();
                param.put("push_records_id",String.valueOf( pushRecords.getId()));
                param.put("object_id",String.valueOf( pushRecords.getObjectId()));
//                if(pushRecords.getArticle() != null && StringUtil.isNotEmpty(pushRecords.getArticle().getId())){
//                    param.put("article_id",String.valueOf( pushRecords.getArticle().getId()));
//
//                }

                //0表示所有人 1表示部分人
                if(StringUtil.isNotEmpty(pushType) && Integer.parseInt(pushType) == 1){


                    String openId = pushRecords.getReceiverIds();//openId 为用户ID

                    //发送消息给部分人
                    sendBoo = YouMengUtil.sendNotificationYouMengAndEasemob(pushRecords.getTitle(),
                            pushRecords.getContent(),openId,openType,param);

                }else{
                    pushRecords.setReceiver("所有人");

//                    List<String> openIds = this.systemService.findListbySql("select id from t_s_user");

                    //发送消息给所有人
                    sendBoo = YouMengUtil.sendSystemMessage(pushRecords.getTitle(),
                            pushRecords.getContent(),openType, null,param);
                }

                //如果发送失败，抛出异常
                if(!sendBoo){

                    throw new Exception("推送消息发送失败,请刷新后重试!");

                }



                message = "推送["+pushRecords.getTitle() + "]成功";
            } catch (Exception e) {
                e.printStackTrace();

                message = "推送["+pushRecords.getTitle()+"]失败,请刷新后重试!";
            }

            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 重新推送推送通知
     * @param id
     * @return
     */
    @RequestMapping(params = "retryPushRecords")
    @ResponseBody
    public AjaxJson retryPushRecords(String id){
        AjaxJson j = new AjaxJson();
        try {

            TPushRecords pushRecords = systemService.get(TPushRecords.class,Integer.parseInt(id));

            if(pushRecords != null){

//                pushRecords.setDeleted(1);

                int openType = 1;//APP中打开方式
                if(pushRecords.getObjectType() == 102){//102表示新闻公告
                    openType = 0;

                }

                boolean sendBoo = false;//默认为false
                //附属参数
                Map<String,String> param = new HashMap<String,String>();
                param.put("push_records_id",String.valueOf( pushRecords.getId()));
                param.put("object_id",String.valueOf( pushRecords.getObjectId()));
//                if(pushRecords.getArticle() != null && StringUtil.isNotEmpty(pushRecords.getArticle().getId())){
//                    param.put("article_id",String.valueOf( pushRecords.getArticle().getId()));
//
//                }

                //0表示所有人 1表示部分人
                if(pushRecords.getReceiverIds() != null && StringUtil.isNotEmpty(pushRecords.getReceiverIds()) ){


                    String openId = pushRecords.getReceiverIds();//openId 为用户ID

                    //发送消息给部分人
                    sendBoo = YouMengUtil.sendNotificationYouMengAndEasemob(pushRecords.getTitle(),
                            pushRecords.getContent(),openId,openType,param);

                }else{

//                    List<String> openIds = this.systemService.findListbySql("select id from t_s_user");

                    //发送消息给所有人
                    sendBoo = YouMengUtil.sendSystemMessage(pushRecords.getTitle(),
                            pushRecords.getContent(),openType, null,param);
                }

                //如果发送失败，抛出异常
                if(!sendBoo){

                    throw new Exception("推送消息发送失败,请刷新后重试!");

                }


                message = "重新推送["+pushRecords.getTitle() + "]成功";


            }else{
                message = "重新推送信息不存在，请刷新重试！";
            }


        } catch (Exception e) {
            e.printStackTrace();
            message = "重新推送id["+id+"]消息失败,请刷新后重试!";
        }

        systemService.addLog(message, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

    /**
     * 删除推送通知管理（非物理删除）
     * @param id
     * @return
     */
    @RequestMapping(params = "delpushRecords")
    @ResponseBody
    public AjaxJson delpushRecords(String id){
        AjaxJson j = new AjaxJson();
        try {

            TPushRecords pushRecords = systemService.get(TPushRecords.class,Long.valueOf(id));

            if(pushRecords != null){

//                pushRecords.setDeleted(1);

                systemService.saveOrUpdate(pushRecords);
                message = "删除推送《"+pushRecords.getTitle() + "》成功";
            }else{
                message = "推送信息不存在，请刷新重试！";
            }


        } catch (Exception e) {

            message = "删除客户资料失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }



}
